import { ref, Ref } from 'vue';

import { Captcha } from '../loginType';

const activeInput = ref(0);

const captchas: Ref<Array<Captcha>> = ref([
    { num: '' },
    { num: '' },
    { num: '' },
    { num: '' },
    { num: '' },
    { num: '' },
]);

const isError = ref(false);

const setFocus = (dom: HTMLElement | null) => {
    if (dom) {
        dom.focus();
    }
};

// 自动校准输入顺序
const handleFocus = (index: number) => {
    const dom = document.getElementById('captcha' + activeInput.value);
    if (index !== activeInput.value) {
        setFocus(dom);
    }
};

// 控制前后方向
const inputDirection = ($event: { keyCode: number }, index: any) => {
    const val = captchas.value[index].num;
    // 回退键处理
    if ($event.keyCode === 8 && val === '') {
        // 重新校准
        const len = captchas.value.filter((nums) => nums.num).length;
        const dom = document.getElementById('captcha' + (index - 1));
        activeInput.value = index - 1;
        if (len === 0) {
            activeInput.value = 0;
            setFocus(document.getElementById('captcha0'));
            return;
        }
        setFocus(dom);
    }
    if ($event.keyCode !== 8 && val !== '') {
        const dom = document.getElementById('captcha' + (index + 1));
        activeInput.value = index + 1;
        setFocus(dom);
    }
};

// 输入框相互联动
const inputFinash = (index: any, value: string) => {
    captchas.value[index].num = !isNaN(Number(value)) ? captchas.value[index].num : '';
    if (!isNaN(Number(value))) {
        const val = captchas.value[index].num;
        activeInput.value = val ? index + 1 : index;
        const dom = document.getElementById('captcha' + activeInput.value);
        setFocus(dom);
    }
};

const setErrorState = (state: boolean) => {
    isError.value = state;
    captchas.value = [{ num: '' }, { num: '' }, { num: '' }, { num: '' }, { num: '' }, { num: '' }];
    activeInput.value = 0;
    setFocus(document.getElementById('captcha0'));
};

const resetPwd = () => {
    setErrorState(false);
    captchas.value = [{ num: '' }, { num: '' }, { num: '' }, { num: '' }, { num: '' }, { num: '' }];
};

export default { inputFinash, inputDirection, handleFocus, setErrorState, resetPwd, captchas, isError };
